﻿using System;
using System.Net;
using System.Text;

namespace Songhay.Net
{
    /// <summary>
    /// Static members for <see cref="System.Net.WebRequest"/>.
    /// </summary>
    public static partial class HttpVerbAsyncUtility
    {
        /// <summary>
        /// Gets the specified resource as a string.
        /// </summary>
        /// <param name="resourceIndicator">The resource indicator.</param>
        /// <param name="getCompleteAction">The get complete action.</param>
        public static void Get(Uri resourceIndicator, Action<object, DownloadStringCompletedEventArgs> getCompleteAction)
        {
            if(getCompleteAction == null) throw new ArgumentNullException("getCompleteAction", "The generic Action is null.");
            var web = new WebClient();
            web.Encoding = Encoding.UTF8;

            if(getCompleteAction != null)
                web.DownloadStringCompleted +=
                    (o, args) => getCompleteAction.Invoke(o, args);

            web.DownloadStringAsync(resourceIndicator);
        }

        /// <summary>
        /// Gets the specified resource as a stream.
        /// </summary>
        /// <param name="resourceIndicator">The resource indicator.</param>
        /// <param name="getCompleteAction">The get complete action.</param>
        public static void Get(Uri resourceIndicator, Action<object, OpenReadCompletedEventArgs> getCompleteAction)
        {
            if(getCompleteAction == null) throw new ArgumentNullException("getCompleteAction", "The generic Action is null.");
            var web = new WebClient();
            web.Encoding = Encoding.UTF8;

            if(getCompleteAction != null)
                web.OpenReadCompleted +=
                    (o, args) => getCompleteAction.Invoke(o, args);
            web.OpenReadAsync(resourceIndicator);
        }

        /// <summary>
        /// Posts the specified resource.
        /// </summary>
        /// <param name="resourceIndicator">The resource indicator.</param>
        /// <param name="postData">The post data.</param>
        /// <param name="postCompleteAction">The post complete action.</param>
        public static void Post(Uri resourceIndicator, string postData, Action<object, UploadStringCompletedEventArgs> postCompleteAction)
        {
            if(postCompleteAction == null) throw new ArgumentNullException("postCompleteAction", "The generic Action is null.");
            var web = new WebClient();
            web.Encoding = Encoding.UTF8;

            if(postCompleteAction != null)
                web.UploadStringCompleted +=
                    (o, args) => postCompleteAction.Invoke(o, args);

            web.UploadStringAsync(resourceIndicator, postData);
        }
    }
}
